package com.scrx.ymg.action;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scrx.ymg.entity.Address;
import com.scrx.ymg.entity.OrderForm;
import com.scrx.ymg.entity.OrderFormDetails;
import com.scrx.ymg.entity.SuperMarketInfo;
import com.scrx.ymg.entity.User;
import com.scrx.ymg.entity.UtilString;
import com.scrx.ymg.service.address.IAddressService;
import com.scrx.ymg.service.orderform.IOrderFormService;
import com.scrx.ymg.service.user.IUserService;
import com.scrx.ymg.util.HttpUtil;
import com.scrx.ymg.util.PayCommonUtil;
import com.scrx.ymg.util.PayConfigUtil;
import com.scrx.ymg.util.XMLUtil;

@Controller
@RequestMapping("/directWCPayAction")
public class DirectWCPayAction {

	@Autowired
	private IOrderFormService orders;
	
	@Autowired
	private IUserService  users;
	
	/**
	 * 测试订单直营
	 * @param product
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value ="/WeChatPayDirectTest",produces = "text/json;charset=UTF-8")
	public String WeChatPayDirectTest(String detailsjson,int userID,Double totalMoney,String addressID){
		Gson gson = new Gson();
		User user=users.findById(userID);
		//SeckillProduct seckill  =kills.getSeckillOne(seckillID);
		//SuperMarketInfo superinfo=sms.findByID(superId);
		List<OrderFormDetails> details =gson.fromJson(detailsjson, new TypeToken<List<OrderFormDetails>>() {}.getType());
		String orderId=orders.createDirectOrderFormNew(user, addressID, totalMoney,details,1);
		if(orderId.equals("251")){//库存不足
			return "251";
		}
		return "";
	}
	
	
	/**
	 * 直营微信支付
	 * @param product
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value ="/WeChatPayDirect",produces = "text/json;charset=UTF-8")
	public String WeChatPayDirect(String detailsjson,int userID,Double totalMoney,String addressID){
		Gson gson = new Gson();
		String urlCode="";
		try {
			User user=users.findById(userID);
			List<OrderFormDetails> details =gson.fromJson(detailsjson, new TypeToken<List<OrderFormDetails>>() {}.getType());
			String orderId=orders.createDirectOrderFormNew(user, addressID, totalMoney,details,-1);
			if(orderId.equals("251")){//库存不足
				return "251";
			}
			Double price=totalMoney*100;
        // 账号信息  
        String appid = PayConfigUtil.APPID;  // appid  
        //String appsecret = PayConfigUtil.APP_SECRET; // appsecret
        String mch_id = PayConfigUtil.MCH_ID; // 商业号  
        String key = PayConfigUtil.API_KEY; // key
        String spbill_create_ip = PayConfigUtil.CREATE_IP; // 获取发起电脑 ip
        String notify_url = PayConfigUtil.ZY_URL; // 回调接口
        String out_trade_no = orderId; // 订单号 
        String body = "美甲商城购物";   // 商品名称 
        String total_fee = Integer.toString(price.intValue()); //订单总金额   注意：价格的单位是分  
        String trade_type = "JSAPI";
        String openid = user.getUserId();
        
        String currTime = PayCommonUtil.getCurrTime();
        String strTime = currTime.substring(8, currTime.length());  
        String strRandom = PayCommonUtil.buildRandom(4) + "";  
        String nonce_str = strTime + strRandom;  //随机字符串
        

        SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();  
        packageParams.put("appid", appid);  
        packageParams.put("mch_id", mch_id);  
        packageParams.put("nonce_str", nonce_str);  
        packageParams.put("body", body);  
        packageParams.put("out_trade_no", out_trade_no);  
        packageParams.put("total_fee", total_fee);  
        packageParams.put("spbill_create_ip", spbill_create_ip);  
        packageParams.put("notify_url", notify_url);  
        packageParams.put("trade_type", trade_type);
        packageParams.put("openid", openid);

        String sign = PayCommonUtil.createSign("UTF-8", packageParams,key);//签名
        packageParams.put("sign", sign);  
          
        
        String requestXML = PayCommonUtil.getRequestXml(packageParams);  

        String resXml = HttpUtil.postData(PayConfigUtil.UFDODER_URL, requestXML);  
      
          
        Map map = XMLUtil.doXMLParse(resXml);
        String prepay_id = (String) map.get("prepay_id");  

        String timeStamp = Long.toString(System.currentTimeMillis()/1000);        
         String stringSignTemp = "appId="+appid+"&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;
         String paySign=PayCommonUtil.sign(stringSignTemp, "&key="+key, "utf-8").toUpperCase();


        UtilString util = new UtilString();
        util.setTimeStamp(timeStamp);
        util.setSignType("MD5");
        util.setNonceStr(nonce_str);
        util.setPackages("prepay_id="+prepay_id);
        util.setPaySign(paySign);
        urlCode=gson.toJson(util);
        //String return_code = (String) map.get("return_code");  
        OrderForm orderForm =orders.getOrderFormByOrderId(orderId);
        orderForm.setPrepayId(prepay_id);
        orders.updateOrderForm(orderForm);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return urlCode;
}
	
	/**	
	 * 直营微信支付回调函数
	 * @throws IOException 
	 * @throws JDOMException 
	 */
	@ResponseBody
	@RequestMapping(value ="/callBackDirectPay",produces = "text/json;charset=UTF-8")
	public void callBackDirectPay(HttpServletRequest request,HttpServletResponse response) throws Exception{
		Logger logger =Logger.getLogger(WeChatPayAction.class);
		logger.info("回调成功"); 
        //读取参数  
        InputStream inputStream ;  
        StringBuffer sb = new StringBuffer();  
        inputStream = request.getInputStream();  
        String s ;  
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));  
        while ((s = in.readLine()) != null){  
            sb.append(s);  
        }  
        in.close();  
        inputStream.close();  
  
        //解析xml成map  
        Map<String, String> m = new HashMap<String, String>();  
        m = XMLUtil.doXMLParse(sb.toString());  
          
        //过滤空 设置 TreeMap  
        SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();        
        Iterator it = m.keySet().iterator();
        while (it.hasNext()) {  
            String parameter = (String) it.next();  
            String parameterValue = m.get(parameter);
              
            String v = "";  
            if(null != parameterValue) {  
                v = parameterValue.trim();  
            }  
            packageParams.put(parameter, v);
        }  
          
        // 账号信息  
        String key = PayConfigUtil.API_KEY; // key  
  
        logger.info(packageParams); 
        String resXml = ""; 
        //判断签名是否正确  
        if(PayCommonUtil.isTenpaySign("UTF-8", packageParams,key)) {
            //------------------------------  
            //处理业务开始  
            //------------------------------  
             
            if("SUCCESS".equals((String)packageParams.get("result_code"))){  
                // 这里是支付成功  
                //////////执行自己的业务逻辑////////////////  
                String mch_id = (String)packageParams.get("mch_id");  
                String openid = (String)packageParams.get("openid");  
                String is_subscribe = (String)packageParams.get("is_subscribe");
                //商户订单号
                String out_trade_no = (String)packageParams.get("out_trade_no");  
                 //订单金额 
                String total_fee = (String)packageParams.get("total_fee"); 
                Gson gson = new Gson();
                OrderForm order = orders.getOrderFormByOrderId(out_trade_no);
                String msg="false";
                if(order.getStatus()==-1){
                    msg=orders.updateOrderFormSendMessage(order);
                }
                //////////执行自己的业务逻辑////////////////  
                //通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
                if(msg.equals("true")){
                	resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"  
                            + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                }else{
                	resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
                            + "<return_msg><![CDATA[重复回调函数]]></return_msg>" + "</xml> ";
                }
            } else {
            	//orders.deleteOrderFormByNum(out_trade_no)
                logger.info("支付失败,错误信息：" + packageParams.get("err_code"));  
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
                        + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";  
            }  
             
        } else{  
        	resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
                    + "<return_msg><![CDATA[签名验证失败]]></return_msg>" + "</xml> ";
            logger.info("通知签名验证失败");  
        }
        //------------------------------  
        //处理业务完毕  
        //------------------------------  
        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());  
        out.write(resXml.getBytes());  
        out.flush();  
        out.close();
        logger.info("回调完成");  
		
	}

}
